package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by Binsabbar on 01/10/2014.
 */
public class MovieLoader extends BibliotecaLoader{

  private ArrayList<Movie> movieList;

  public MovieLoader() {
    movieList = new ArrayList<Movie>(5);
  }


  public Movie[] readMoviesFromFile(String pathToFile, String fileName){
    try{
      BufferedReader fileReader = super.getFile(pathToFile, fileName);
      if (fileReader == null) return null;

      String line = fileReader.readLine();
      while(line != null){
        Movie aMovie = creatMovieFromFileLine(line);
        if(aMovie != null) movieList.add(aMovie);
        line = fileReader.readLine();
      }
      fileReader.close();
      if (movieList.size() > 0) return movieList.toArray(new Movie[movieList.size()]);
    }
    catch (IOException ignored){
      return null;
    }
    return null;
  }

  public Movie creatMovieFromFileLine(String line){
    String[] parsedLine = line.split(",");
    if (parsedLine.length != 5) return null;

    String [] movieComponents = new String[5];
    for (int i = 0; i < parsedLine.length; i++) {
      movieComponents[i] = parsedLine[i].trim();
      if (movieComponents[i].isEmpty()) return null;
    }

    int releaseYear;
    int rating;
    try{
      releaseYear = Integer.parseInt(movieComponents[1]);
      rating = Integer.parseInt(movieComponents[4]);
    }
    catch (NumberFormatException e){
      return null;
    }

    Director director = new Director(movieComponents[2], movieComponents[3]);
    return new Movie(movieComponents[0], releaseYear, director, rating);
  }
}
